package doantotnghiep.daoimpl;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;

import doantotnghiep.dao.ProviderDao;
import doantotnghiep.model.Provider;

public class ProviderDaoImpl implements ProviderDao{
	
	@Autowired
	private HibernateTemplate hibernateTemplate;

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
	}

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	@Override
	public void deleteProvider(int id) {
		Provider entity = this.findProviderByID(id);
		if (entity != null){
			entity.setStatus(1);
			this.hibernateTemplate.saveOrUpdate(entity);
		}	
	}

	@Override
	public void saveProvider(Provider provider) {
		this.hibernateTemplate.saveOrUpdate(provider);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Provider> listProvider() {
	
		List<Provider> list = hibernateTemplate.find("from Provider where status = 0");
		if(list!=null){
			return list;
		}
		return null;
	}

	@Override
	public void addProvider(Provider provider) {
		this.hibernateTemplate.saveOrUpdate(provider);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Provider findProviderByID(int id) {
		List<Provider> providers = hibernateTemplate.find("from Provider where MaCT ="+ id+" and status = 0");
		if(providers!=null){
			return providers.get(0);
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Provider> getProviderByKey(String key) {
		List<Provider> list= hibernateTemplate.find("from Provider where fullName like '%"+key+"%' and status = 0");
		if(list!=null){
			return list;
		}
		return null;
	}
}

